<?php

namespace V1\Model;
/**
 * 用户Session
 *
 * @property   $name Description
 * 
 * @author wangzhenxian
 * @package application.components 
 */
use Think\Model;
class UserSessionModel extends Model {
     

     protected $partition = array(
       'field' =>'user_id',
       'type' => 'mod',
       'num' =>'10',
     );
    protected $_auto = array(
        array('token', 'mt_data_token',self::MODEL_INSERT,'function'),
        array('client', 'mt_data_client',self::MODEL_BOTH,'function'),
        array('login_time',NOW_TIME,self::MODEL_BOTH),
        array('expires_time','mt_data_expires',self::MODEL_BOTH,'function',MT_MAX_SESSION_EXPIRE_TIME),
    );
    /**
     * 添加session
     * @param type $uid 用户ID
     * @return type
     */
    public function writeUserSession($uid)
    {
          $data = array(
                   'user_id' => $uid,
                   'times' => 0,
           );
           /* 添加session */
           if($this->create($data)){
                   $id = $this->add();
                   return $id ? $id : 0; //0-未知错误，大于0-添加成功
           } else {
                   return $this->getError(); //错误详情见自动验证注释
           }
    }
    /**
     * 更新用户登录次数，token有效期信息
     * @param type $uid
     * @param type $token
     */
    public function updateExpiresTime($uid,$token)
    {
//          $where = array(
//                   'user_id' => $uid,
//                   'token' => $token,
//           );
//           $this->where($where)->setInc('times',1);
            $where = array(
                   'user_id' => $uid,
                   'token' => $token,
           );
            
           $this->where($where)->setField('expires_time',  mt_data_expires(MT_MAX_SESSION_EXPIRE_TIME));
    }
    /**
     * 返回用户Token
     * @param type $uid
     * @return type
     */
    public function getUserToken($uid)
    {
        return $this->where(array('user_id'=>(int)$uid,'expires_time' => array('gt',NOW_TIME),))->getField('token');
    }
    /**
     * 检查token是否过期
     * @param  type $token
     * @return type 
     */
    public function checkExpireTime($token)
    {
          $where = array(
                'token' => $token,
               'expires_time' => array('gt',NOW_TIME),
           );
          $uid = $this->where($where)->getField('user_id');
          return $uid; 
    }
     
}
